import { createElement, useEffect, useState, useRef } from 'rax';
import View from 'rax-view';
import Image from 'rax-image';
import Text from 'rax-text';
import ScrollView from 'rax-scrollview';
import { usePageShow, getSearchParams } from 'rax-app';
import {
  queryUserInfo,
  queryUserPoints,
  queryUserHistory,
  queryPointsRedeem,
  postUserInvitations,
  postUserSubscription
} from '@/api';
import NavBar from '@/components/NavBar';
import { share } from '@uni/apis';
import './index.css';

const Task = () => {
  const app = getApp();
  const [isFavor, setIsFavor] = useState(true);
  const [isOpened, setIsOpened] = useState(false);
  const [titleBarHeight, setTitleBarHeight] = useState(0);
  const [point, setPoint] = useState(0);
  const [userInfo, setUserInfo] = useState({});
  const [list, setList] = useState([]);
  const [hasMore, setHasMore] = useState(true);
  const pageNo = useRef(1);
  
  usePageShow(() => {
    let params = getSearchParams();
    setIsFavor(params.isFavor);
    my.getSystemInfo({
      success: (res) => {
        let height = res.titleBarHeight + res.statusBarHeight
        setTitleBarHeight(height)
      }
    });
    onLoadData();
    onLoadPoint();
    onLoadHistory();
  })

  const onPostInvitations = async()=>{
    await postUserInvitations();
    onLoadData();
  }

  const onLoadPoint = () => {
    queryUserPoints({})
      .then(res=>{
        setPoint(res.currentPoint);
      })
  }

  const onLoadData = () => {
    queryUserInfo({})
      .then(res=>{
        setUserInfo(res);
      })
  }

  const onLoadHistory = () => {
    let params = {
      page: pageNo.current,
      page_size: 20
    }
    queryUserHistory(params)
      .then(res=>{
        let data = res.list || [];
        let arr = [];
        if (pageNo.current === 1) {
          arr = data;
        } else {
          arr = [...list, ...data];
        }
        if (res.list.length < 20) {
          setHasMore(false)
        }
        setList(arr);
      })
  }

  const onLoadMore = () => {
    if (hasMore) {
      pageNo.current = pageNo.current + 1;
      onLoadHistory();
    }
  }

  const doBack = () => {
    share({
      title: '快来围观我的写真吧',
      path: '/pages/index/index',
      imageUrl: 'https://jala-test-images.sndaurl.cn/images/share_img.png'
    })
  }

  const onShowHistory = () => {
    setIsOpened(true);
  }

  const onRedeem = () => {
    queryPointsRedeem({user_type: 'taobao'})
      .then(res=>{
        if (res.Code == 454) {
          my.showToast({
            content: '积分不足',
            type: 'none',
            zIndex: 9999
          })
        } else {
          onLoadData();
        }
      })
  }

  const onShare = () => {
    my.showSharePanel();
  }

  const onFavorShop = () => {
    if (isFavor) {
      return;
    }
    my.tb.favorShop({
      id: 1652554937,
      success: function (res) {
        setIsFavor(true);
        app.globalData.isFavorShop = true;
        my.showToast({
          content: '订阅成功',
          type: 'none',
          zIndex: 9999
        })
        updateUserSubscription();
      }
    })
  }

  const updateUserSubscription = async() => {
    await postUserSubscription({});
    onLoadData();
  }
  
  return (
    <View className='task_container'>
      <NavBar
        title="任务中心"
        onClick={()=>{doBack()}}
      />
      <View
        className='task_section'
        style={{
          paddingTop: `${titleBarHeight}px`
        }}
      >
        <View className='task_main'>
          <View className='task_main_info'>
            <View className='task_main_info_title'>剩余变妆次数</View>
            <View className='task_main_info_value'>
              <Text className='task_main_info_value_num'>{userInfo?.num || 0}</Text>
              次
            </View>
          </View>
          <View className='task_main_history' onClick={()=>{onShowHistory()}}>
            历史明细
            <Image
              source={{
                uri: 'https://jala-test-images.sndaurl.cn/images/right.png'
              }}
              mode='aspectFill'
              className='task_main_history_icon'
            />
          </View>
          <View className='task_main_content'>
            <View className='task_main_content_title'>
              <Image
                className='task_main_content_title_icon'
                source={{
                  uri:'https://jala-test-images.sndaurl.cn/images/task_title.png'
                }}
                mode='widthFix'
              />
            </View>
            <View className='task_main_content_section'>
              <Image
                source={{
                  uri:'https://jala-test-images.sndaurl.cn/images/arrowBg.png'
                }}
                mode='aspectFill'
                className='task_main_content_section_icon'
              />
              <View className='task_main_content_section_title'>加入会员（1/1）</View>
              <View className='task_main_content_section_desc w_406'>变妆次数+3，活动期间限一次</View>
              <View className={`task_main_content_section_action pedding`}>
                已完成
              </View>
            </View>
            <View className='task_main_content_section'>
              <Image
                source={{
                  uri:'https://jala-test-images.sndaurl.cn/images/arrowBg.png'
                }}
                mode='aspectFill'
                className='task_main_content_section_icon'
              />
              <View className='task_main_content_section_title'>邀请好友（{userInfo.invitations}/5）</View>
              <View className='task_main_content_section_desc w_406'>成功邀请1位用户，即可获得1次变妆机会</View>
              {
                userInfo.invitations == 5 ? (
                  <View  className='task_main_content_section_action pedding'>已完成</View>
                ) : (
                  <button
                    open-type="share"
                    className={`task_main_content_section_action`}
                    onClick={()=>{
                      my.showSharePanel();
                      onLoadData();
                    }}
                  >
                    完成任务
                  </button>
                )
              }
            </View>
            <View className='task_main_content_section'>
              <Image
                source={{
                  uri:'https://jala-test-images.sndaurl.cn/images/arrowBg.png'
                }}
                mode='aspectFill'
                className='task_main_content_section_icon'
              />
              <View className='task_main_content_section_title'>订阅店铺（{userInfo.subscription == 1 ? 1 : 0}/1）</View>
              <View className='task_main_content_section_desc w_406'>首次订阅关注店铺，变妆次数+1，活动期间限1次</View>
              <View className={`task_main_content_section_action ${userInfo.subscription == 1 ? 'pedding' : ''}`} onClick={()=>{onFavorShop()}}>
                {userInfo.subscription == 1 ? '已完成' : '完成任务'}
              </View>
            </View>
            <View className='task_main_content_section'>
              <Image
                source={{
                  uri:'https://jala-test-images.sndaurl.cn/images/arrowBg.png'
                }}
                mode='aspectFill'
                className='task_main_content_section_icon'
              />
              <View className='task_main_content_section_title'>积分兑换（当前积分：{point}）</View>
              <View className='task_main_content_section_desc w_406'>自然堂100会员积分可兑换1次变妆机会，不限次数</View>
              <button className={`task_main_content_section_action`} onClick={()=>{onRedeem()}}>
                完成任务
              </button>
            </View>
            <View className='task_main_content_section'>
              <Image
                source={{
                  uri:'https://jala-test-images.sndaurl.cn/images/arrowBg.png'
                }}
                mode='aspectFill'
                className='task_main_content_section_icon'
              />
              <View className='task_main_content_section_title'>获取更多积分</View>
              <View className='task_main_content_section_desc w_574'>可微信搜索“自然堂官方商城”小程序进行购买商品，即可获取会员积分</View>
            </View>
          </View>
        </View>
      </View>
      {
        isOpened ? (
          <View className='mask'>
            <View className='history_view'>
              <View className='history_view_title'>
                历史明细
                <Image
                  source={{
                    uri:'https://jala-test-images.sndaurl.cn/images/closeIcon.png'
                  }}
                  mode='aspectFill'
                  className='history_view_title_icon'
                  onClick={()=>{setIsOpened(false)}}
                />
              </View>
              <ScrollView
                scrollY={true}
                style={{
                  height: '640rpx'
                }}
                className='history_view_content'
                onEndReached={()=>{onLoadMore()}}
              >
                {
                  list && list.map((item, index) =>
                    <View className='history_view_content_section' key={index}>
                      <View className='history_view_content_section_title'>{item.desc}</View>
                      <View className='history_view_content_section_time'>生成时间：{item.create_time}</View>
                      <View className='history_view_content_section_value'>{item.num}</View>
                    </View>
                  )
                }
              </ScrollView>
            </View>
          </View>
        ) : null
      }
    </View>
  )
}
export default Task;
